import 'dart:math';

import 'package:get/get.dart';
import 'package:number_spark_flutter/network/ns_api.dart';
import 'package:number_spark_flutter/pages/ns_home/single/ns_single_logic.dart';
import 'package:number_spark_flutter/routes/ns_app_pages.dart';
import 'package:number_spark_flutter/utils/ns_log_report_utils.dart';

class NSBaseController extends GetxController {
  doClickTermsOfUser() {
    Get.toNamed(NSRoutes.webView, arguments: {'webUrl': NSApi.termConditions, 'title': 'Terms and Conditions'});
    NSLogReportUtils.stat(page: NSLogPages.nsUserTerms);
  }

  doClickPrivacyPolicy() {
    Get.toNamed(NSRoutes.webView, arguments: {'webUrl': NSApi.privacyPolicy, 'title': 'Privacy Policy'});
    NSLogReportUtils.stat(page: NSLogPages.nsPrivacy);
  }

  // 随机生成一个加减乘除的表达式，结果为整数，并生成选项
  Question generateQuestion() {
    final random = Random();

    // 随机生成两个操作数，范围是 1 到 100
    int num1 = random.nextInt(100) + 1;
    int num2 = random.nextInt(100) + 1;

    // 随机选择运算符（0: 加, 1: 减, 2: 乘, 3: 除）
    int operatorIndex = random.nextInt(4);
    late String operator;
    late int result;

    switch (operatorIndex) {
      case 0: // 加法
        operator = '+';
        result = num1 + num2;
        break;
      case 1: // 减法
        operator = '-';
        // 确保结果非负
        if (num1 < num2) {
          int temp = num1;
          num1 = num2;
          num2 = temp;
        }
        result = num1 - num2;
        break;
      case 2: // 乘法
        operator = '×';
        result = num1 * num2;
        break;
      case 3: // 除法
        operator = '÷';
        // 确保整除，重新生成 num2
        while (num1 % num2 != 0) {
          num2 = random.nextInt(99) + 1; // 避免 0
        }
        result = num1 ~/ num2; // 使用整除符号
        break;
    }

    // 生成选项，确保包含正确答案
    List<int> options = _generateOptions(result, random);
    // 随机放置正确答案
    int correctIndex = random.nextInt(4);
    options[correctIndex] = result;
    return Question(expression: '$num1 $operator $num2 = ', options: options, answer: result, correctIndex: correctIndex);
  }

  // 生成与正确答案相近的选项
  List<int> _generateOptions(int result, Random random) {
    Set<int> options = {};
    while (options.length < 4) {
      int delta = random.nextInt(10) + 1; // 偏差范围为 ±1 到 ±10
      int option = random.nextBool() ? result + delta : result - delta;
      if (option > 0) {
        options.add(option); // 确保选项为正数
      }
    }
    return options.toList();
  }
}
